'use client';

import { useState } from 'react';

interface InventoryAdjustModalProps {
  isOpen: boolean;
  onClose: () => void;
  onAdjust: (data: { productId: number; adjustment: number; type: 'in' | 'out'; notes: string }) => void;
  product: {
    id: number;
    productId: number;
    productName: string;
    productSku: string;
    quantity: number;
    lowStockThreshold: number;
  } | null;
}

export default function InventoryAdjustModal({ isOpen, onClose, onAdjust, product }: InventoryAdjustModalProps) {
  const [adjustment, setAdjustment] = useState('');
  const [type, setType] = useState<'in' | 'out'>('in');
  const [notes, setNotes] = useState('');
  const [loading, setLoading] = useState(false);

  if (!isOpen || !product) return null;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    const adjustValue = parseInt(adjustment);
    if (!adjustValue || adjustValue <= 0) {
      alert('请输入有效的调整数量');
      return;
    }

    setLoading(true);
    try {
      await onAdjust({
        productId: product.productId,
        adjustment: adjustValue,
        type,
        notes
      });
      
      // 重置表单
      setAdjustment('');
      setNotes('');
      onClose();
    } catch (error) {
      console.error('调整库存失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const getNewQuantity = () => {
    if (!adjustment) return product.quantity;
    const adjustValue = parseInt(adjustment);
    if (type === 'in') return product.quantity + adjustValue;
    return product.quantity - adjustValue;
  };

  return (
    <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div className="mt-3">
          <h3 className="text-lg font-medium text-gray-900 mb-4">
            调整库存 - {product.productName}
          </h3>
          
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                当前库存
              </label>
              <div className="text-lg font-semibold">{product.quantity}</div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                调整类型
              </label>
              <div className="flex space-x-4">
                <label className="inline-flex items-center">
                  <input
                    type="radio"
                    value="in"
                    checked={type === 'in'}
                    onChange={(e) => setType(e.target.value as 'in' | 'out')}
                    className="form-radio"
                  />
                  <span className="ml-2">入库</span>
                </label>
                <label className="inline-flex items-center">
                  <input
                    type="radio"
                    value="out"
                    checked={type === 'out'}
                    onChange={(e) => setType(e.target.value as 'in' | 'out')}
                    className="form-radio"
                  />
                  <span className="ml-2">出库</span>
                </label>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                调整数量 *
              </label>
              <input
                type="number"
                value={adjustment}
                onChange={(e) => setAdjustment(e.target.value)}
                min="1"
                required
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请输入数量"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                调整后库存
              </label>
              <div className={`text-lg font-semibold ${
                getNewQuantity() <= product.lowStockThreshold ? 'text-orange-600' : 'text-green-600'
              }`}>
                {getNewQuantity()}
                {getNewQuantity() <= product.lowStockThreshold && (
                  <span className="text-sm text-orange-600 ml-2">(低于阈值)</span>
                )}
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                备注
              </label>
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                rows={3}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请输入调整原因或备注"
              />
            </div>

            <div className="flex justify-end space-x-3 pt-4">
              <button
                type="button"
                onClick={onClose}
                className="px-4 py-2 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50"
              >
                取消
              </button>
              <button
                type="submit"
                disabled={loading || !adjustment}
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
              >
                {loading ? '处理中...' : '确认调整'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}